package org.openea.eap.module.obpm.service.custchart;

import org.openbpm.base.db.dboper.DbOperator;
import org.openbpm.base.db.dboper.DbOperatorFactory;
import org.openbpm.base.db.model.table.Column;
import org.openbpm.base.db.model.table.Table;
import org.openbpm.base.manager.impl.BaseServiceImpl;
import org.openbpm.form.api.constant.FormCustChartObjType;
import org.openea.eap.module.obpm.mapper.custchart.FormCustChartMapper;
import org.openea.eap.module.obpm.model.custchart.FormCustChart;
import org.openbpm.sys.api.model.ISysDataSource;
import org.openbpm.sys.api.service.ISysDataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class FormCustChartManagerImpl extends BaseServiceImpl<FormCustChartMapper, FormCustChart> implements FormCustChartManager {

    @Autowired
    private FormCustChartMapper formCustChartMapper;

    @Autowired
    ISysDataSourceService sysDataSourceService;


    public Map<String, String> searchObjName(FormCustChart formCustChart) {
        ISysDataSource sysDataSource = this.sysDataSourceService.getByKey(formCustChart.getDsKey());
        JdbcTemplate jdbcTemplate = this.sysDataSourceService.getJdbcTemplateByKey(formCustChart.getDsKey());
        Map<String, String> map = new HashMap<>();
        DbOperator dbOperator = DbOperatorFactory.newOperator(sysDataSource.getDbType(), jdbcTemplate);

        if (FormCustChartObjType.TABLE.equalsWithKey(formCustChart.getObjType())) {
            map = dbOperator.getTableNames(formCustChart.getObjName());
        } else if (FormCustChartObjType.SQL.equalsWithKey(formCustChart.getObjType())) {
            // TODO
        }
        return map;
    }

    @Override
    public Table<Column> getTable(FormCustChart formCustChart) {
        try {
            ISysDataSource sysDataSource = this.sysDataSourceService.getByKey(formCustChart.getDsKey());
            JdbcTemplate jdbcTemplate = this.sysDataSourceService.getJdbcTemplateByKey(formCustChart.getDsKey());
            DbOperator dbOperator = DbOperatorFactory.newOperator(sysDataSource.getDbType(), jdbcTemplate);
            Table<Column> table = null;

            if (FormCustChartObjType.TABLE.equalsWithKey(formCustChart.getObjType())) {
                table = dbOperator.getTable(formCustChart.getObjName());
            } else if (FormCustChartObjType.SQL.equalsWithKey(formCustChart.getObjType())) {
                //table = dbOperator.getView(formCustChart.getObjName());
                // TODO 根据SQL获取字段，参考定制SQL字段解析
            }
            return table;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
